<!--用做 数据字段模板-->
<template>
  <div class="ky-container">
    <el-card shadow="hover" class="ky-card ky-card-xs ky-card-hdbg">
      <section class="header-section">
        <el-form :inline="true" class="m-t-1 apply-card ky-form-inline ky-form-inline-sm">
          <el-form-item label="医院名称" label-width="80px" prop="hospitalCode">
            <el-select style="width:100%" size="small" filterable v-model="listQuery.hospitalCode" @change="changeHosp" placeholder="请选择医院">
              <el-option
                v-for="item in mx_hospitalList"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="影像区域" label-width="80px" prop="depArea">
            <el-select style="width:100%" size="small" v-model="listQuery.depArea" @change="changeDepArea" placeholder="请选择" clearable>
              <el-option
                v-for="item in depAreaOptions"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="检查部门" label-width="80px" prop="dep">
            <el-select style="width:100%" size="small" v-model="listQuery.dep" @change="changeDep" placeholder="请选择" clearable>
              <el-option
                v-for="item in depOptions"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="设备类型" label-width="80px" prop="modality">
            <el-select style="width:100%" size="small" v-model="listQuery.modality" placeholder="请选择" filterable clearable>
              <el-option
                v-for="item in modalityOptions"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="类型" label-width="80px" v-if="isShowTypeBox">
            <el-select size="small" v-model="type" placeholder="请选择" filterable clearable multiple collapse-tags @change="changeType">
              <el-option
                v-for="item in typeOptions"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="项目" label-width="80px" prop="item">
            <el-input size="small" v-model="listQuery.item" clearable></el-input>
          </el-form-item>
          <el-form-item label-width="40px">
            <el-button type="primary" class="m-l-0" icon="el-icon-search" size="small" @click="search">查询</el-button>
            <el-button
              class="add-button"
              v-permission="'YJYY10005015'"
              type="primary"
              size="small"
              @click="handleAdd"><i class="el-icon-plus icon"></i>添加</el-button>
          </el-form-item>
        </el-form>
      </section>
    </el-card>
    <div class="quickfilter-content ky-mt10">
      <el-card v-show="quickFilterStatus" shadow="hover" class="qf-sidebar ky-card ky-card-hdbg">
        <div class="content-title">
          <span>快速查询</span>
          <i class="el-icon-arrow-left ky-fr ky-pointer ky-ft16 ky-fw600" @click="quickFilterStatus = false"></i>
        </div>
        <HospTypeFilter
          ref="hospTypeFilter"
          :hospital-code="listQuery.hospitalCode"
          @treeChange="treeChange"></HospTypeFilter>
      </el-card>
      <el-card shadow="hover" class="qf-box ky-card ky-card-hdbg">
        <section class="content-section">
          <div class="content-title">
            <i class="el-icon-arrow-right ky-pointer ky-ft16 ky-fw600" v-show="!quickFilterStatus" @click="quickFilterStatus = true"></i>
            <span>数据字典列表</span>
            <!-- <el-button class="add-button" v-permission="'YJYY10005015'" type="primary" size="small" @click="handleAdd"><i class="el-icon-plus icon"></i>添加</el-button> -->
          </div>
          <el-table v-loading="loading" size="medium" :data="itemTable" border class="ky-table">
            <el-table-column label="操作" width="170" v-if="$hasPermission(['YJYY10005016','YJYY10005017'])">
              <template slot-scope="scope">
                <div class="flex flex-row justify-center text-center">
                  <el-button
                    type="primary"
                    style="margin-right:6px;"
                    @click="handleEdit(scope.$index, scope.row)"
                    size="small"
                    v-permission="'YJYY10005016'"
                  ><i class="el-icon-edit"></i> 编辑</el-button>
                  <el-button
                    type="danger"
                    style="margin-right:6px;"
                    @click="handleDelete(scope.$index, scope.row)"
                    size="small"
                    v-permission="'YJYY10005017'"
                  ><i class="el-icon-delete"></i> 删除</el-button>
                </div>
              </template>
            </el-table-column>
            <!-- <el-table-column prop="hospitalCode" label="医院名称" :formatter="frtHospCode" align="center" min-width="200"></el-table-column> -->
            <el-table-column prop="depArea" label="影像区域" align="center" min-width="100"></el-table-column>
            <el-table-column prop="dep" label="检查部门" align="center" min-width="100"></el-table-column>
            <el-table-column prop="modality" label="设备类型" align="center" min-width="100"></el-table-column>
            <el-table-column prop="type" label="类型" align="center" min-width="160"></el-table-column>
            <el-table-column prop="item" label="项目" align="center" min-width="200"></el-table-column>
            <el-table-column prop="itemPy" label="项目拼音" align="center" min-width="200"></el-table-column>
            <el-table-column prop="itemValue" label="项目值" align="center" width="200" show-overflow-tooltip></el-table-column>
            <el-table-column prop="sortid" label="排序" align="center" min-width="100"></el-table-column>
            <!-- <el-table-column prop="department" label="科室" align="center"> </el-table-column> -->
            <!-- <el-table-column prop="checkRoom" label="检查机房" align="center"> </el-table-column> -->
          </el-table>
          <paginationCont
            :total="totalCount"
            :page.sync="currentPage"
            :limit.sync="pageSize"
            @pagination="fetchData"
          />
        </section>
      </el-card>
    </div>
    <DicInsertDialog
      :dic-data="curRow"
      :dialog-dic-visible="dialogDicVisible"
      @myClose="handleDicClose"
      @refreshDic="refreshDic"></DicInsertDialog>
  </div>
</template>
<script>
import {
  getDepAreaList, getDepList, getModalityTypeList,
  getItemPages, getTypeGroupList, deleteItemList, getItemList } from '@/api/api.js'
import { Options } from '@/utils/constant'
import paginationCont from '@/components/Pagination/index'
import HospTypeFilter from '@/components/treeFilter/hospitalTypeTree'
import DicInsertDialog from './dicInsertDialog'
export default {
  name: 'Dictionary',
  components: {
    paginationCont,
    DicInsertDialog,
    HospTypeFilter
  },
  data() {
    return {
      isShowTypeBox: true,
      options: Options,
      depArea: [],
      dep: [],
      modality: [],
      checkRoom: [],
      checkClass: [],
      type: [],
      listQuery: {
        type: '',
        hospitalCode: '',
        depArea: '',
        dep: '',
        modality: '',
        item: '',
        department: ''
      },
      typeOptions: [], //
      departmentOptions: [], // 科室
      depAreaOptions: [],
      depOptions: [], // 检查部门
      modalityOptions: [], // 设备类型
      totalCount: 0,
      pageSize: 10,
      currentPage: 1,
      itemTable: [],
      detailTable: [],
      curStatus: false,
      loading: false,
      dialogDicVisible: false,
      curRow: {},
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },

      // 快速查询
      quickFilterStatus: true
    }
  },
  created() {
    this.$getHospitalList()
    this.init()
  },
  mounted() {
    if (this.$hasPermission(['YJYY100050177'])) {
      this.isShowTypeBox = false
    }
    // this.$nextTick(() => {
    //   this.$refs.hospTypeFilter && this.$refs.hospTypeFilter.init()
    // })
  },
  methods: {
    init() {
      this.listQuery.hospitalCode = this.$store.state.user.hospitalCode || this.mx_hospitalList[0].code
      if (this.$route.query.type) {
        this.type = [this.$route.query.type]
      }
      this.changeHosp('init')
      // this.search()
    },
    search() {
      this.currentPage = 1
      this.fetchData()
    },
    fetchData() {
      if (!this.listQuery.hospitalCode) {
        this.$message.warning('请选择医院')
        return
      }
      this.loading = true
      this.listQuery.type = this.type.join(',')
      this.listQuery.pageSize = this.pageSize
      this.listQuery.pageNumber = this.currentPage

      getItemPages(this.listQuery).then(async res => {
        this.loading = false
        if (res && res.code === 10000) {
          this.itemTable = res.content.list
          this.totalCount = res.content.totalCount
        }
      }).catch(() => {
        this.loading = false
      })
    },
    getType(clearable) {
      const params = {
        HospitalCode: this.listQuery.hospitalCode
      }
      getTypeGroupList(params).then(res => {
        if (res && res.code === 10000) {
          this.typeOptions = res.content.list
          if (clearable) {
            this.type = []
          }
        }
      })
    },
    getDepAreaOptions() {
      return new Promise(async resolve => {
        await getDepAreaList({ hospitalCode: this.listQuery.hospitalCode }).then(res => {
          if (res.code === 10000) {
            this.depAreaOptions = res.content.list
            resolve(res)
          }
        })
      })
    },
    getDepOptions() {
      const params = {
        hospitalCode: this.listQuery.hospitalCode,
        depArea: this.listQuery.depArea
      }
      return new Promise(async resolve => {
        await getDepList(params).then(res => {
          if (res.code === 10000) {
            this.depOptions = res.content.list
            resolve(res)
          }
        })
      })
    },
    getModalityOptions() {
      const params = {
        hospitalCode: this.listQuery.hospitalCode,
        depArea: this.listQuery.depArea,
        dep: this.listQuery.dep
      }
      return new Promise(async resolve => {
        await getModalityTypeList(params).then(res => {
          if (res.code === 10000) {
            this.modalityOptions = res.content.list
            resolve(res)
          }
        })
      })
    },
    getDepartment() {
      let data = {
        HospitalCode: this.listQuery.hospitalCode,
        DepArea: this.listQuery.depArea,
        type: '科室'
      }
      return new Promise(async resolve => {
        await getItemList(data).then(res => {
          if (res && res.code === 10000) {
            this.departmentOptions = res.content.list.map(_item => _item.item)
            resolve(res)
          }
        })
      })
    },
    changeHosp(type) {
      console.log(type)
      if (!this.listQuery.hospitalCode) return
      // 关联：影像、检查部门、检查分组、设备类型、检查机房
      this.typeOptions = []
      this.depAreaOptions = []
      this.depOptions = []
      this.modalityOptions = []
      // this.departmentOptions = []
      type !== 'init' ? this.type = [] : ''
      this.listQuery.depArea = ''
      this.listQuery.dep = ''
      this.listQuery.modality = ''

      this.itemTable = []
      this.totalCount = 0
      // this.listQuery.department = ''
      try {
        this.getDepAreaOptions()
        this.getDepOptions()
        this.getModalityOptions()
        //  this.getDepartment()
        if (type === 'init') {
          this.getType()
        } else {
          this.getType(true)
          this.search()
        }
        this.$nextTick(() => {
          const _type = this.type.length === 1 ? this.type[0] : ''
          this.$refs.hospTypeFilter && this.$refs.hospTypeFilter.init(_type)
        })
      } catch (err) {
        console.log(err)
      }
    },
    changeDepArea() {
      // if (!this.listQuery.depArea) return
      // 关联：检查部门、科室
      this.depOptions = []
      this.modalityOptions = []
      this.listQuery.dep = ''
      this.listQuery.modality = ''
      try {
        this.getDepOptions()
        this.getModalityOptions()
      } catch (err) {
        console.log(err)
      }
    },
    changeDep() {
      // if (!this.listQuery.dep) return
      // 关联：检查分组、设备类型、检查机房
      this.modalityOptions = []
      this.listQuery.modality = ''
      try {
        this.getModalityOptions()
      } catch (err) {
        console.log(err)
      }
    },
    changeType() {
      this.$refs.hospTypeFilter && this.$refs.hospTypeFilter.reset()
    },
    handleAdd() {
      this.dialogDicVisible = true
      this.curRow.hospitalCode = this.listQuery.hospitalCode
      this.curRow.type = this.type && this.type.length === 1 ? this.type[0] : ''
    },
    handleEdit(i, row) {
      this.dialogDicVisible = true
      this.curRow = row
      console.log('this.curRow', this.curRow)
    },
    handleDicClose() {
      this.curRow = {}
      this.dialogDicVisible = false
    },
    refreshDic() {
      this.$nextTick(() => {
        const _type = this.type.length === 1 ? this.type[0] : ''
        this.$refs.hospTypeFilter && this.$refs.hospTypeFilter.init(_type)
      })
      this.getType(false)
      this.handleDicClose()
      this.fetchData()
    },
    handleDelete(i, row) {
      this.$confirm('此操作将永久删除该字典, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteData(row)
      })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    deleteData(row) {
      // 清空右边
      let data = {
        id: row.id,
        hospitalCode: row.hospitalCode
      }
      deleteItemList(data).then(res => {
        if (res && res.code === 10000) {
          this.fetchData()
          this.$message.success('删除成功')
        }
      })
    },
    // 格式化医院code
    frtHospCode(row, column, cellValue, index) {
      let name = ''
      let hospIndex = this.mx_hospitalList.findIndex(item => item.code === cellValue)
      if (hospIndex !== -1) {
        name = this.mx_hospitalList[hospIndex].name
      }
      return name
    },

    // 快速查询返回
    treeChange(data) {
      let type = data.type
      this.type = type ? [type] : []
      this.search()
    }
  }
}
</script>
<style lang="scss" scoped>
.ky-container{
  .content-title{
    margin-bottom: 10px;
    span{
      font-size: 16px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 600;
    }
    .add-button{
      height: 32px;
      margin-left: 16px;
    }
  }
}
</style>
